package br.gov.ana.controllers;

import static br.gov.ana.controllers.util.ConstUtils.MAX_ITENS_POR_PAGINA;
import br.gov.ana.controllers.util.JsfUtil;
import br.gov.ana.controllers.util.PaginationHelper;
import br.gov.ana.entities.*;
import br.gov.ana.facade.MunicipioFacade;
import br.gov.ana.facade.SubbaciaRioFacade;
import br.gov.ana.facade.UsinaLocalizacaoFacade;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;
import java.util.ResourceBundle;
import javax.ejb.EJB;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.SessionScoped;
import javax.faces.component.UIComponent;
import javax.faces.context.FacesContext;
import javax.faces.convert.Converter;
import javax.faces.convert.FacesConverter;
import javax.faces.model.DataModel;
import javax.faces.model.ListDataModel;
import javax.faces.model.SelectItem;

/**
 *
 * @author lucas.nunes
 */
@ManagedBean(name = "usinaLocalizacaoController")
@SessionScoped
public class UsinaLocalizacaoController implements Serializable {

    private UsinaLocalizacao current;
    private Subbacia subbacia = new Subbacia();
    private SubbaciaRio subbaciaRio = new SubbaciaRio();
    private DataModel items = null;
    @EJB
    private br.gov.ana.facade.UsinaLocalizacaoFacade ejbFacade;
    private PaginationHelper pagination;
    private int selectedItemIndex;
    private List<UsinaLocalizacao> lista;
    @EJB
    private br.gov.ana.facade.MunicipioFacade municipioFacade;
    @EJB
    private br.gov.ana.facade.SubbaciaRioFacade subbaciaRioFacade;
         
    private static final String ORDER = "uslId";
    
    
    /**
     *
     */
    public UsinaLocalizacaoController() {
    }

    /**
     *
     * @return
     */
    public SubbaciaRioFacade getSubbaciaRioFacade() {
        return subbaciaRioFacade;
    }

    /**
     *
     * @param subbaciaRioFacade
     */
    public void setSubbaciaRioFacade(SubbaciaRioFacade subbaciaRioFacade) {
        this.subbaciaRioFacade = subbaciaRioFacade;
    }

    /**
     *
     * @return
     */
    public SubbaciaRio getSubbaciaRio() {
        return subbaciaRio;
    }

    /**
     *
     * @param subbaciaRio
     */
    public void setSubbaciaRio(SubbaciaRio subbaciaRio) {
        this.subbaciaRio = subbaciaRio;
    }

    /**
     *
     * @return
     */
    public Subbacia getSubbacia() {
        return subbacia;
    }

    /**
     *
     * @param subbacia
     */
    public void setSubbacia(Subbacia subbacia) {
        this.subbacia = subbacia;
    }

    /**
     *
     * @return
     */
    public List<UsinaLocalizacao> getLista() {
        if (lista == null || lista.size() != ejbFacade.count()) {
            lista = new ArrayList<UsinaLocalizacao>();
            lista = ejbFacade.findAll(ORDER);
        }
        return lista;
    }

    /**
     *
     * @param lista
     */
    public void setLista(List<UsinaLocalizacao> lista) {
        this.lista = lista;
    }

    /**
     *
     * @param current
     */
    public void setSelectedUsinaLocalizacao(UsinaLocalizacao current) {
        this.current = current;
    }

    /**
     *
     * @return
     */
    public UsinaLocalizacao getSelectedUsinaLocalizacao() {
        return this.current;
    }

    /**
     *
     * @return
     */
    public UsinaLocalizacao getSelected() {
        if (current == null) {
            current = new UsinaLocalizacao();
            selectedItemIndex = -1;
        }
        return current;
    }

    private UsinaLocalizacaoFacade getFacade() {
        return ejbFacade;
    }

    private MunicipioFacade getMunicipioFacade() {
        return this.municipioFacade;
    }

    /**
     *
     */
    public void carregaRios() { // SUBBACIA
        if (current.getUslRioCd() != null) {
            subbacia = getSubbaciaRioFacade().findSubbaciaByRio(current.getUslRioCd());
        }

    }

    /**
     *
     * @return
     */
    public PaginationHelper getPagination() {
        if (pagination == null) {
            pagination = new PaginationHelper(MAX_ITENS_POR_PAGINA) {

                @Override
                public int getItemsCount() {
                    return getFacade().count();
                }

                @Override
                public DataModel createPageDataModel() {
                    return new ListDataModel(getFacade().findRange(new int[]{getPageFirstItem(), getPageFirstItem() + getPageSize()}));
                }
            };
        }
        return pagination;
    }

    /**
     *
     * @return
     */
    public String prepareList() {
        recreateModel();
        return "List";
    }

    /**
     *
     * @return
     */
    public String prepareView() {
        //current = (UsinaLocalizacao) getItems().getRowData();
        //selectedItemIndex = pagination.getPageFirstItem() + getItems().getRowIndex();
        if (current == null) {
            JsfUtil.addErrorMessage(ResourceBundle.getBundle("/Bundle").getString("NoItemSelected"));
            return "List";
        } else {
            subbacia = getSubbaciaRioFacade().findSubbaciaByRio(current.getUslRioCd());
            return "View";
        }
    }

    /**
     *
     * @return
     */
    public String prepareCreate() {
        recreateModel();
        subbacia = new Subbacia();
        current = new UsinaLocalizacao();
        selectedItemIndex = -1;
        return "Create";
    }

    /**
     *
     * @return
     */
    public String create() {
        try {
            // Colocar nas outras logicas, por exemplo update.
            if (getFacade().findByUsinaRio(current)) {
                getFacade().create(current);
                JsfUtil.addSuccessMessage(ResourceBundle.getBundle("/Bundle").getString("UsinaLocalizacaoCreated"));
                return prepareCreate();

            } else {
                JsfUtil.addErrorMessage(ResourceBundle.getBundle("/Bundle").getString("MsgRelacionamentoUsinaRio"));
                return null;
            }


        } catch (Exception e) {
            JsfUtil.addErrorMessage(e, ResourceBundle.getBundle("/Bundle").getString("PersistenceErrorOccured"));
            return null;
        }
    }

    /**
     *
     * @return
     */
    public String prepareEdit() {
        //current = (UsinaLocalizacao) getItems().getRowData();
        //selectedItemIndex = pagination.getPageFirstItem() + getItems().getRowIndex();

        if (current == null) {
            JsfUtil.addErrorMessage(ResourceBundle.getBundle("/Bundle").getString("NoItemSelected"));
            return "List";
        } else {
            subbacia = getSubbaciaRioFacade().findSubbaciaByRio(current.getUslRioCd());
            return "Edit";
        }
    }

    /**
     *
     * @return
     */
    public String update() {
        try {
            if (current == null) {
                JsfUtil.addErrorMessage(ResourceBundle.getBundle("/Bundle").getString("NoItemSelected"));
                return "Edit";
            } else {
                if (getFacade().findByUsinaRio(current)) {
                    getFacade().edit(current);
                    JsfUtil.addSuccessMessage(ResourceBundle.getBundle("/Bundle").getString("UsinaLocalizacaoUpdated"));
                    return "View";
                } else {
                    JsfUtil.addErrorMessage(ResourceBundle.getBundle("/Bundle").getString("MsgRelacionamentoUsinaRio"));
                    return null;
                }
            }
        } catch (Exception e) {
            JsfUtil.addErrorMessage(e, ResourceBundle.getBundle("/Bundle").getString("PersistenceErrorOccured"));
            return null;
        }
    }

    /**
     *
     * @return
     */
    public String destroy() {
        //current = (UsinaLocalizacao) getItems().getRowData();
        //selectedItemIndex = pagination.getPageFirstItem() + getItems().getRowIndex();
        performDestroy();
        //recreatePagination();
        recreateModel();
        return "List";
    }

    private void performDestroy() {
        try {
            if (current == null) {
                JsfUtil.addErrorMessage(ResourceBundle.getBundle("/Bundle").getString("NoItemSelected"));
            } else {
                getFacade().remove(current);
                JsfUtil.addSuccessMessage(ResourceBundle.getBundle("/Bundle").getString("UsinaLocalizacaoDeleted"));
            }
        } catch (Exception e) {
            JsfUtil.addErrorMessage(e, ResourceBundle.getBundle("/Bundle").getString("PersistenceErrorOccured"));
        }
    }

    /**
     *
     */
    public void carregaMunicipios() {
    }

    private void updateCurrentItem() {
        int count = getFacade().count();
        if (selectedItemIndex >= count) {
            // selected index cannot be bigger than number of items:
            selectedItemIndex = count - 1;
            // go to previous page if last page disappeared:
            if (pagination.getPageFirstItem() >= count) {
                pagination.previousPage();
            }
        }
        if (selectedItemIndex >= 0) {
            current = getFacade().findRange(new int[]{selectedItemIndex, selectedItemIndex + 1}).get(0);
        }
    }

    /**
     *
     * @return
     */
    public DataModel getItems() {
        if (items == null) {
            items = getPagination().createPageDataModel();
        }
        return items;
    }

    private void recreateModel() {
        current = new UsinaLocalizacao();
        lista = null;
        //items = null;
    }

    private void recreatePagination() {
        pagination = null;
    }

    /**
     *
     * @return
     */
    public String next() {
        getPagination().nextPage();
        recreateModel();
        return "List";
    }

    /**
     *
     * @return
     */
    public String previous() {
        getPagination().previousPage();
        recreateModel();
        return "List";
    }

    /**
     *
     * @return
     */
    public SelectItem[] getItemsAvailableSelectMany() {
        return JsfUtil.getSelectItems(ejbFacade.findAll(), false);
    }

    /**
     *
     * @return
     */
    public SelectItem[] getItemsAvailableSelectOne() {
        return JsfUtil.getSelectItems(ejbFacade.findAll(), true);
    }

    /**
     *
     * @return
     */
    public SelectItem[] getItemsAvailableSelectOneMunicipioByUf() {
        if (current.getUslUfdCd() != null) {
            return JsfUtil.getSelectItems(getMunicipioFacade().findMunicipioByUf(current.getUslUfdCd()), true);
        } else {
            return JsfUtil.getSelectItems(new ArrayList<Municipio>() {
            }, true);
        }

    }

    /**
     *
     * @return
     */
    public SelectItem[] getItemsAvailableSelectOneRiosBySubbacia() {
        if (subbacia != null) {
            return JsfUtil.getSelectItems(getSubbaciaRioFacade().findRioBySubbacia(subbacia), true);
        } else {
            return JsfUtil.getSelectItems(new ArrayList<Rio>() {
            }, true);
        }

    }

    /**
     *
     */
    @FacesConverter(forClass = UsinaLocalizacao.class)
    public static class UsinaLocalizacaoControllerConverter implements Converter {

        /**
         *
         * @param facesContext
         * @param component
         * @param value
         * @return
         */
        @Override
        public Object getAsObject(FacesContext facesContext, UIComponent component, String value) {
            if (value == null || value.length() == 0) {
                return null;
            }
            UsinaLocalizacaoController controller = (UsinaLocalizacaoController) facesContext.getApplication().getELResolver().
                    getValue(facesContext.getELContext(), null, "usinaLocalizacaoController");
            return controller.ejbFacade.find(getKey(value));
        }

        java.math.BigDecimal getKey(String value) {
            java.math.BigDecimal key;
            key = new java.math.BigDecimal(value);
            return key;
        }

        String getStringKey(java.math.BigDecimal value) {
            StringBuilder sb = new StringBuilder();
            sb.append(value);
            return sb.toString();
        }

        /**
         *
         * @param facesContext
         * @param component
         * @param object
         * @return
         */
        @Override
        public String getAsString(FacesContext facesContext, UIComponent component, Object object) {
            if (object == null) {
                return null;
            }
            if (object instanceof UsinaLocalizacao) {
                UsinaLocalizacao o = (UsinaLocalizacao) object;
                return getStringKey(o.getUslId());
            } else {
                throw new IllegalArgumentException("object " + object + " is of type " + object.getClass().getName() + "; expected type: " + UsinaLocalizacaoController.class.getName());
            }
        }
    }
}
